package com.xzl.xep.web.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xzl.xep.common.utils.StringUtil;
import com.xzl.xep.exception.BusinessException;
import com.xzl.xep.pojo.Product;
import com.xzl.xep.service.ProductService;

@Controller
@RequestMapping(value ="/product" )
public class ProductController extends BaseController {

	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
	
	@Autowired
	private ProductService service;
	
	
	@RequestMapping(value ="", method=RequestMethod.GET )
	public String product(Model model) {
		model.addAttribute("productList", service.getProducts(companyId));
		return "product/manage";
	}
	
	@RequestMapping(value ="/add", method=RequestMethod.GET )
	public String addProduct() {
		
		return "product/add";
	}
	
	
	@RequestMapping(value ="/add", method=RequestMethod.POST )
	@ResponseBody
	public Product newCunstomer(Product product) {
	
		
		if(StringUtil.isEmpty(product.getCode()))
			throw new BusinessException("简码不能为空！");
		
		if(StringUtil.isEmpty(product.getName()))
			throw new BusinessException("名称不能为空！");
		
		
		if(product.getPrice() == null || product.getPrice() == 0d)
			throw new BusinessException("价格不能为空！");
		
		
		if(!service.checkCustomerExists(product))
			throw new BusinessException("简码或民称已存在！");
		
		return service.addProduct(product);
		
	}
		 
	
	@RequestMapping(value ="/startUsing/{id}" )
	@ResponseBody
	public String startUsing(@PathVariable long id) {
		return  setProductStatus(id,1);
	}
		 
	
	@RequestMapping(value ="/stopUsing/{id}" )
	@ResponseBody
	public String stopUsing(@PathVariable long id) {
		return setProductStatus(id,0);
	
	}
	
	@RequestMapping(value ="/del/{id}" )
	@ResponseBody
	public String del(@PathVariable long id) {
		return setProductStatus(id,-1);
	
	}
	
	
	private String setProductStatus(long id, int status){
		Product product = service.loadObject(Product.class, id);
		if(product != null){
			product.setStatus(status);
			service.updateObject(product);
		}
		return "success";
	}
	
	
	@RequestMapping(value ="/queryCode" )
	@ResponseBody
	public List<Product> queryCode(String term) {
		return service.queryCode(companyId,term);
	} 
	
	
	
}
